<?php

require_once 'Vega/Cache/Engine/Abstract.php';

class Vega_Cache_Engine_Memcached extends Vega_Cache_Engine_Abstract
{

    /**
     * Memcache object
     *
     * @var Memcache
     */
    protected $_memcache = null;


    public function __construct($options)
    {
        /*if (!class_exists('Memcache'))
        {
            require_once 'Vega/Cache/Engine/Exception.php';
            throw new Vega_Cache_Engine_Exception('Memcache extension must be installed');
        }*/


        if (!isset($options['lifetime']) || empty($options['lifetime']))
        {
            require_once 'Vega/Cache/Engine/Exception.php';
            throw new Vega_Cache_Engine_Exception('A lifetime must be specified');
        }

        
        if (!isset($options['use_compressed']))
        {
            $options['use_compressed'] = false;
        }

        $this->_memcache = new Memcache();

        $tmp = 0;
        foreach ($options['servers'] as $server)
        {
            if (!isset($server['host']))
            {
                continue;
            }

            if ($tmp > 0)
            {
                $this->_memcache->addServer($server['host'], (isset($server['port']) ? $server['port'] : 11211));
            }
            else
            {
                $this->_memcache->connect($server['host'], (isset($server['port']) ? $server['port'] : 11211));
            }
            $tmp++;
        }
        
        $this->_options = $options;
    }

    /**
     * Saves
     *
     * @param string $name
     * @param string $data
     * @param integer $lifetime
     */
    public function save($name, $data, $lifetime = null)
    {
        // get the default lifetime
        if (null == $lifetime)
        {
            $lifetime = $this->_options['lifetime'];
        }

        $name = $this->getId($name);
        return $this->_memcache->set($name, $data, $this->_options['use_compressed'], $lifetime);
    }

    /**
     * Loads
     *
     * @param string $name
     * @return mixed
     */
    public function load($name)
    {
        $name = $this->getId($name);
        return $this->_memcache->get($name);
    }

    /**
     * Deletes
     *
     * @param string $name
     * @return boolean
     */
    public function delete($name)
    {
        $name = $this->getId($name);
        return $this->_memcache->delete($name);
    }

    public function isExpired($name, $lifetime = null)
    {
        $name = $this->getId($name);

        if ($this->_memcache->get($name))
        {
            return false;
        }
        return true;
    }

    /**
     * Close the memcache connection
     *
     * @return boolean
     */
    public function disconnect()
    {
        return $this->_memcache->close();
    }
}

